package org.jeecg.modules.demo.allvipcard.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.allvipcard.entity.AllVipcard;
import org.jeecg.modules.demo.allvipcard.service.IAllVipcardService;
import org.jeecg.modules.demo.basemembersharevip.entity.BaseMemberShareVip;
import org.jeecg.modules.demo.basemembersharevip.service.IBaseMemberShareVipService;
import org.jeecg.modules.demo.basemembertoreceivevip.entity.BaseMemberToReceiveVip;
import org.jeecg.modules.demo.basemembertoreceivevip.service.IBaseMemberToReceiveVipService;
import org.jeecg.modules.demo.basemembertoreceivevipcoupon.entity.BaseMemberToReceiveVipCoupon;
import org.jeecg.modules.demo.basemembertoreceivevipcoupon.service.IBaseMemberToReceiveVipCouponService;
import org.jeecg.modules.demo.basemembervip.entity.BaseMemberVip;
import org.jeecg.modules.demo.basemembervip.service.IBaseMemberVipService;
import org.jeecg.modules.demo.basemembervipcoupon.entity.BaseMemberVipCoupon;
import org.jeecg.modules.demo.basemembervipcoupon.service.IBaseMemberVipCouponService;
import org.jeecg.modules.demo.castcardrecord.entity.CastCardRecord;
import org.jeecg.modules.demo.castcardrecord.service.ICastCardRecordService;
import org.jeecg.modules.demo.couponmanagement.entity.CouponManagement;
import org.jeecg.modules.demo.couponmanagement.service.ICouponManagementService;
import org.jeecg.modules.demo.issuingrecords.entity.IssuingRecords;
import org.jeecg.modules.demo.issuingrecords.service.IIssuingRecordsService;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.shareholdervipcard.entity.ShareholderVipCard;
import org.jeecg.modules.demo.shareholdervipcard.service.IShareholderVipCardService;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.vipcardcoupon.entity.VipCardCoupon;
import org.jeecg.modules.demo.vipcardcoupon.service.IVipCardCouponService;
import org.jeecg.modules.demo.vipcarddrawrecord.entity.VipcardDrawRecord;
import org.jeecg.modules.demo.vipcarddrawrecord.service.IVipcardDrawRecordService;
import org.jeecg.modules.util.DebugUtils;
import org.jeecg.modules.util.HttpUtils;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;

import static org.jeecg.modules.util.RedisUtils.storeId;

/**
 * 全部贵宾卡
 */
@Api(tags = "全部贵宾卡")
@RestController
@RequestMapping("/allvipcard/allVipcard")
@Slf4j
public class AllVipcardController extends JeecgController<AllVipcard, IAllVipcardService> {
    @Autowired
    private IAllVipcardService allVipcardService;
    @Autowired
    private ICouponManagementService couponManagementService;
    @Autowired
    private IIssuingRecordsService issuingRecordsService;
    @Autowired
    private IVipCardCouponService vipCardCouponService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IBaseMemberVipService baseMemberVipService;
    @Autowired
    private IBaseMemberVipCouponService baseMemberVipCouponService;
    @Autowired
    private IShareholderVipCardService shareholderVipCardService;
    @Autowired
    private IBaseMemberToReceiveVipService baseMemberToReceiveVipService;
    @Autowired
    private IBaseMemberToReceiveVipCouponService baseMemberToReceiveVipCouponService;
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private ICastCardRecordService castCardRecordService;
    @Autowired
    private IVipcardDrawRecordService vipcardDrawRecordService;


    @Autowired
    private RedisUtils redisUtils;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "全部贵宾卡-分页列表查询")
    @ApiOperation(value = "全部贵宾卡-分页列表查询", notes = "全部贵宾卡-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AllVipcard allVipcard,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<AllVipcard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, allVipcard, req.getParameterMap());
        Page<AllVipcard> page = new Page<AllVipcard>(pageNo, pageSize);
        IPage<AllVipcard> pageList = allVipcardService.page(page, queryWrapper);
        List<AllVipcard> records = pageList.getRecords();
        for (AllVipcard av : records) {
            // 关联优惠劵数量
            List<VipCardCoupon> list = vipCardCouponService.list(new QueryWrapper<VipCardCoupon>()
                    .eq("store_id", storeId)
                    .eq("vip_id", av.getId()));
            Integer ticketNum = list.stream().map(VipCardCoupon::getNum).reduce(Integer::sum).orElse(0);
            av.setTicketNum(ticketNum);
            if ("免费".equals(av.getIsFree())) {
                av.setSellingPrice(null);
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     */
    @AutoLog(value = "全部贵宾卡-添加")
    @ApiOperation(value = "全部贵宾卡-添加", notes = "全部贵宾卡-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AllVipcard allVipcard, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        allVipcard.setStoreId(storeId);

        // 当前店铺全部贵宾卡
        List<AllVipcard> list = allVipcardService.list(new QueryWrapper<AllVipcard>().eq("store_id", storeId));
        // list中与allVipcard同名的贵宾卡个数
        long count = list.stream().filter(av -> av.getCardName().equals(allVipcard.getCardName())).count();
        if (count > 0) {
            return Result.error("添加失败，该店铺已有同名贵宾卡！");
        }
        if (allVipcard.getCardType() != null && allVipcard.getCardType().equals("新人卡")) {
            long count1 = list.stream().filter(av -> "新人卡".equals(av.getCardType())).count();
            if (count1 > 0) {
                return Result.error("添加失败，新人卡只能有一张！");
            }
        }
        if ("付费".equals(allVipcard.getIsFree())) {
            if (allVipcard.getSellingPrice() == null) {
                return Result.error("添加失败，付费的贵宾卡价格必填！");
            }
            if (allVipcard.getSellingPrice() <= 0) {
                return Result.error("添加失败，贵宾卡价格需要大于0！");
            }
            if ("是".equals(allVipcard.getIsRewardShareholders())) {
                if (allVipcard.getShareholdersBonus() == null) {
                    return Result.error("添加失败，给股东分红则必填分红金额！");
                }
                if (allVipcard.getShareholdersBonus() <= 0) {
                    return Result.error("添加失败，股东分红金额需要大于0！");
                }
                if (allVipcard.getSellingPrice() < allVipcard.getShareholdersBonus()) {
                    return Result.error("添加失败，股东分红金额不能高于贵宾卡价格！");
                }
            }
        } else {
            // 默认免费，若传null，也设置为免费
            allVipcard.setIsFree("免费");
            allVipcard.setSellingPrice(null);
            if ("是".equals(allVipcard.getIsRewardShareholders())) {
                return Result.error("添加失败，付费卡才可以给股东分红！");
            }
        }
        if ("通用卡".equals(allVipcard.getCardType())) {
            // 设置默认值
            if (StringUtils.isEmpty(allVipcard.getCanCollectAgain())) {
                allVipcard.setCanCollectAgain("否");
            }
            if (StringUtils.isEmpty(allVipcard.getIsNewOnly())) {
                allVipcard.setIsNewOnly("是");
            }
        }

        allVipcard.setCardId(getNewCode(storeId));
        allVipcard.setCreditNumber(0);
        allVipcardService.save(allVipcard);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     */
    @AutoLog(value = "全部贵宾卡-编辑")
    @ApiOperation(value = "全部贵宾卡-编辑", notes = "全部贵宾卡-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AllVipcard allVipcard, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        // 当前店铺全部贵宾卡（除自己）
        List<AllVipcard> list = allVipcardService.list(new QueryWrapper<AllVipcard>()
                .eq("store_id", storeId)
                .ne("id", allVipcard.getId()));
        // list中与allVipcard同名的贵宾卡个数
        long count = list.stream().filter(av -> av.getCardName().equals(allVipcard.getCardName())).count();
        if (count > 0) {
            return Result.error("编辑失败，该店铺已有同名贵宾卡！");
        }
        if (allVipcard.getCardType() != null && allVipcard.getCardType().equals("新人卡")) {
            long count1 = list.stream().filter(av -> "新人卡".equals(av.getCardType())).count();
            if (count1 > 0) {
                return Result.error("编辑失败，新人卡只能有一张！");
            }
        }
        if ("付费".equals(allVipcard.getIsFree())) {
            if (allVipcard.getSellingPrice() == null) {
                return Result.error("编辑失败，付费的贵宾卡价格必填！");
            }
            if (allVipcard.getSellingPrice() <= 0) {
                return Result.error("编辑失败，贵宾卡价格需要大于0！");
            }
            if ("是".equals(allVipcard.getIsRewardShareholders())) {
                if (allVipcard.getShareholdersBonus() == null) {
                    return Result.error("编辑失败，给股东分红则必填分红金额！");
                }
                if (allVipcard.getShareholdersBonus() <= 0) {
                    return Result.error("编辑失败，股东分红金额需要大于0！");
                }
                if (allVipcard.getSellingPrice() < allVipcard.getShareholdersBonus()) {
                    return Result.error("编辑失败，股东分红金额不能高于贵宾卡价格！");
                }
            }
        } else {
            // 免费
            if ("是".equals(allVipcard.getIsRewardShareholders())) {
                return Result.error("编辑失败，付费卡才可以给股东分红！");
            }
        }
        allVipcardService.updateById(allVipcard);
        return Result.OK("编辑成功！");
    }

    @Autowired
    private IBaseMemberShareVipService baseMemberShareVipService;

    /**
     * 通过id删除
     */
    @AutoLog(value = "全部贵宾卡-通过id删除")
    @ApiOperation(value = "全部贵宾卡-通过id删除", notes = "全部贵宾卡-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(HttpServletRequest req,@RequestParam(name = "id", required = true) String id) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        //删除股东可分享的贵宾卡
        {
            // 查询实卡
            AllVipcard allVipcard = allVipcardService.getById(id);
            List<BaseMemberShareVip> vips = baseMemberShareVipService.list(new QueryWrapper<BaseMemberShareVip>().eq("store_id", storeId).eq("card_id", allVipcard.getCardId()));
            List<String> vIdList = new ArrayList<>();
            for (BaseMemberShareVip ele : vips) {
                vIdList.add(ele.getId());
            }
            if(vIdList.size()>0){
                baseMemberShareVipService.removeByIds(vIdList);
            }
        }
        allVipcardService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "全部贵宾卡-批量删除")
    @ApiOperation(value = "全部贵宾卡-批量删除", notes = "全部贵宾卡-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@NotNull @RequestParam(name = "ids", required = true) String ids) {
        this.allVipcardService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "全部贵宾卡-通过id查询")
    @ApiOperation(value = "全部贵宾卡-通过id查询", notes = "全部贵宾卡-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AllVipcard allVipcard = allVipcardService.getById(id);
        if (allVipcard == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(allVipcard);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AllVipcard allVipcard) {
        //return super.exportXls(request, allVipcard, AllVipcard.class, "全部贵宾卡");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<AllVipcard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, allVipcard, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<AllVipcard> pageList = allVipcardService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "全部贵宾卡"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, AllVipcard.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("全部贵宾卡数据", "导出人:" + user.getRealname(), "全部贵宾卡");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AllVipcard.class);
    }

    //获取贵宾卡编码
    @AutoLog(value = "全部贵宾卡-获取贵宾卡编码")
    @ApiOperation(value = "全部贵宾卡-获取贵宾卡编码", notes = "全部贵宾卡-获取贵宾卡编码")
    @GetMapping(value = "/getProjectNum")
    public Result<?> getProjectNum(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        return Result.OK(getNewCode(storeId));
    }

    private int getNewCode(String storeId) {
        QueryWrapper<AllVipcard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.orderByDesc("card_id").last("limit 1");
        AllVipcard bean = allVipcardService.getOne(queryWrapper);
        if (bean == null || bean.getCardId() == null) {
            return 1;
        }
        return bean.getCardId() + 1;
    }

    //获取优惠劵列表
    @AutoLog(value = "全部贵宾卡-关联优惠劵查询")
    @ApiOperation(value = "全部贵宾卡-关联优惠劵查询", notes = "全部贵宾卡-关联优惠劵查询")
    @GetMapping(value = "/queryCouponList")
    public Result<?> queryCouponList(
            @RequestParam(name = "id", required = true) String id,
            @RequestParam(name = "ticketName", required = false) String ticketName,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("storeId", storeId);
        params.put("vipId", id);
        params.put("ticketName", ticketName);
        Page<CouponManagement> page = new Page<>(pageNo, pageSize);
        // 注意这里id是关联表的id，num也取自关联表
        IPage<CouponManagement> pageList = allVipcardService.queryCouponList(page, params);
        return Result.OK(pageList);
    }

    //添加优惠劵
    @AutoLog(value = "全部贵宾卡-添加优惠劵")
    @ApiOperation(value = "全部贵宾卡-添加优惠劵", notes = "全部贵宾卡-添加优惠劵")
    @GetMapping(value = "/addCoupon")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> addCoupon(String vipId, String ids) {
        String[] list = ids.split(",");
        for (String id : list) {
            QueryWrapper<VipCardCoupon> query = new QueryWrapper<>();
            query.eq("vip_id", vipId);
            query.eq("coupon_id", id);
            VipCardCoupon role = vipCardCouponService.getOne(query);
            if (role == null) {
                CouponManagement vipCardCoupon = couponManagementService.getById(id);
                role = new VipCardCoupon();
                BeanUtils.copyProperties(vipCardCoupon, role);
                role.setCouponId(id);
                role.setVipId(vipId);
                role.setId(null);
                role.setCreateTime(new Date());
                String num = vipCardCoupon.getNum();
                if (oConvertUtils.isEmpty(num)) {
                    role.setNum(1);
                }
                vipCardCouponService.save(role);
                log.info(role.getId());
            }
        }
        return Result.OK("添加成功！");
    }

    //删除优惠劵
    @AutoLog(value = "全部贵宾卡-删除关联的优惠劵")
    @ApiOperation(value = "全部贵宾卡-删除关联的优惠劵", notes = "全部贵宾卡-删除关联的优惠劵")
    @DeleteMapping(value = "/deleteCoupon")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> deleteCoupon(String vipId, String ids) {
        String[] list = ids.split(",");
        for (String id : list) {
            QueryWrapper<VipCardCoupon> query = new QueryWrapper<>();
            query.eq("vip_id", vipId);
            query.eq("coupon_id", id);
            VipCardCoupon role = vipCardCouponService.getOne(query);
            if (role != null) {
                vipCardCouponService.removeById(role);
            }
        }
        return Result.OK("删除成功！");
    }


    //-优惠劵下发与领取展示逻辑-------------------------------------------------------------------------------------------------------

    /**
     * 贵宾卡 下发
     *
     * @param vipId     贵宾卡ID
     * @param memberIds 下发到指定人的id集合
     * @param num       下发数量
     */
    @AutoLog(value = "全部贵宾卡-下发")
    @ApiOperation(value = "全部贵宾卡-下发", notes = "全部贵宾卡-下发")
    @GetMapping(value = "/sendCoupon")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> sendCoupon(@RequestParam("vipId") String vipId, @RequestParam("memberIds") String memberIds, @RequestParam("num") Integer num, HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        return allVipcardService.setIssuing(vipId, memberIds, num, storeId);
    }

    /**
     * 贵宾卡 生成二维码
     *
     * @param vipId 贵宾卡ID
     * @param num   下发数量
     */
    @AutoLog(value = "全部贵宾卡-生成二维码")
    @ApiOperation(value = "全部贵宾卡-生成二维码", notes = "全部贵宾卡-生成二维码")
    @GetMapping(value = "/qrCode")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> qrCode(@RequestParam("vipId") String vipId, @RequestParam("num") Integer num, @RequestParam("page") String page, @RequestParam("env_version") String env_version
            , HttpServletRequest req, HttpServletResponse res) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        StoreInfo store = storeInfoService.getById(storeId);
        if (store == null) {
            return Result.error("店铺不存在");
        }
        String xcxAppId = store.getXcxAppId();
        String xcxAppSecret = store.getXcxAppSecret();
        if (StringUtils.isEmpty(xcxAppId) || StringUtils.isEmpty(xcxAppSecret)) {
            return Result.error("店铺还未绑定小程序");
        }

        if (num <= 0) {
            return Result.error("生成失败，数量需要大于0！");
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        AllVipcard av = allVipcardService.getById(vipId);
        if (av == null) {
            return Result.error("没有查到贵宾卡记录");
        }
        if (!"通用卡".equals(av.getCardType())) {
            return Result.error("只有通用卡可以生成二维码");
        }
        // 关联优惠劵数量
        List<VipCardCoupon> list = vipCardCouponService.list(new QueryWrapper<VipCardCoupon>()
                .eq("store_id", storeId)
                .eq("vip_id", av.getId()));
        Integer ticketNum = list.stream().map(VipCardCoupon::getNum).reduce(Integer::sum).orElse(0);
        if (ticketNum == 0) {
            return Result.error("贵宾卡还未关联优惠劵");
        }
        av.setTicketNum(ticketNum);
        if ("免费".equals(av.getIsFree())) {
            av.setSellingPrice(null);
        }
        // 贵宾卡关联的优惠劵，数量已从关联表中带出
        List<CouponManagement> cmList = allVipcardService.listCouponsByVipId(vipId, storeId);

        IssuingRecords issuing = new IssuingRecords();
        issuing.setDrawTime(new Date());
        issuing.setCirculation(num);
        issuing.setCurrentAllowance(num);
        issuing.setQuantityReceived(0);
        issuing.setToStoreNum(0);
        issuing.setOperator(sysUser.getRealname());
        issuing.setStoreId(storeId);
        issuing.setVipId(vipId);
        issuing.setVipName(av.getCardName());
        issuing.setMemberName("生成二维码");

        issuingRecordsService.save(issuing);

        BaseMemberToReceiveVip toReceiveVip = new BaseMemberToReceiveVip();
        BeanUtils.copyProperties(av, toReceiveVip);
        toReceiveVip.setId(null);
        toReceiveVip.setCreateTime(null);
        toReceiveVip.setCreateBy(null);
        toReceiveVip.setUpdateTime(null);
        toReceiveVip.setUpdateBy(null);
        toReceiveVip.setType("2");
        toReceiveVip.setIssuingRecordsId(issuing.getId());
        toReceiveVip.setStatus("0");

        toReceiveVip.setShareNum(num);
        baseMemberToReceiveVipService.save(toReceiveVip);

        for (CouponManagement coupon : cmList) {
            BaseMemberToReceiveVipCoupon toReceiveVipCoupon = new BaseMemberToReceiveVipCoupon();
            BeanUtils.copyProperties(coupon, toReceiveVipCoupon);
            toReceiveVipCoupon.setId(null);
            toReceiveVipCoupon.setCreateTime(null);
            toReceiveVipCoupon.setCreateBy(null);
            toReceiveVipCoupon.setUpdateTime(null);
            toReceiveVipCoupon.setUpdateBy(null);
            toReceiveVipCoupon.setToReceiveVipId(toReceiveVip.getId());
            toReceiveVipCoupon.setNum(Integer.parseInt(coupon.getNum()));
            baseMemberToReceiveVipCouponService.save(toReceiveVipCoupon);
        }
        av.setCreditNumber(av.getCreditNumber() + 1);
        allVipcardService.updateById(av);

        String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + xcxAppId + "&secret=" + xcxAppSecret;
        String result1 = HttpUtils.sendGet(url1);
        String token2 = TokenUtils.getTokenByRequest(req);
        System.out.println("管理端的token:" + token2);
        System.out.println("请求token的url:" + result1);
        JSONObject resultJson1 = JSON.parseObject(result1);
        String errcode = resultJson1.getString("errcode");
        if (errcode != null && !"0".equals(errcode)) {
            log.debug("获取accessToken返回值异常，错误码：{}", errcode);
            return Result.error("获取accessToken返回值异常，错误码：" + errcode + "result：" + resultJson1);
        }
        String accessToken = resultJson1.getString("access_token");
        System.out.println("返回的token:" + accessToken);
/*
        String url2 = "https://api.weixin.qq.com/wxa/d?access_token=" + accessToken;
        System.out.println("生成二维码的地址:"+url2);
        JSONObject params1 = new JSONObject();
        if (hasVedio(av)){
            //贵宾视频卡
            params1.put("scene", "vipId=" + toReceiveVip.getId()+ "&type=3");
            params1.put("page", "pages/shipin/index");
        }else {
            params1.put("scene", "vipId=" + toReceiveVip.getId() + "&type=3");
            params1.put("page", page);
        }
        params1.put("check_path", false);
        params1.put("env_version", env_version);
        params1.put("is_hyaline", true);
        System.out.println("生成二维码的地址:"+url2);
        HttpUtils.sendPostJsonWriteRes(params1, url2, res);
*/

        String url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        JSONObject params1 = new JSONObject();


/*
        if (hasVedio(av)){
            params1.put("scene", "shareVipId=" + toReceiveVip.getId()+ "&type=3");
            params1.put("page", "pages/shipin/index");
        }else{
            params1.put("scene",  "vipId=" + toReceiveVip.getId()+ "&type=3");
            params1.put("page", page);
        }*/

        if (hasVedio(av)) {
            params1.put("scene", "vipId=" + toReceiveVip.getId() + "&type=3");
            params1.put("page", "pages/shipin/index");
        } else {
            params1.put("scene", "vipId=" + toReceiveVip.getId() + "&type=3");
            params1.put("page", page);
        }
        params1.put("check_path", false);
        params1.put("env_version", env_version);
        params1.put("is_hyaline", true);
        System.out.println("生成二维码的地址:" + url2);
        HttpUtils.sendPostJsonWriteRes(params1, url2, res);
        return null;
    }

    private boolean hasVedio(AllVipcard av) {
        return av.getVedioId() != null && av.getVedioId().trim().length() > 0;
    }

    /**
     * 会员或股东分享优惠卡 调用此接口生成一个静态链接地址 暂无生成
     *
     * @param sendId 分享人的ID
     * @param vipId  分享的贵宾卡ID
     */
    @AutoLog(value = "全部贵宾卡-会员或股东分享优惠卡")
    @ApiOperation(value = "全部贵宾卡-会员或股东分享优惠卡", notes = "全部贵宾卡-会员或股东分享优惠卡")
    @GetMapping(value = "/shareCoupon")
    @Transactional(rollbackFor = JeecgBootException.class)//事物
    public Result<?> shareCoupon(String sendId, String vipId) {
        BaseMemberVip baseMemberVip = baseMemberVipService.getById(vipId);
        Map<String, Object> vipMap = ToolsUtils.objectToMap(baseMemberVip);
        Map<String, Object> map = new HashMap<>(vipMap);
        map.put("sendId", sendId);
        map.put("vipId", baseMemberVip.getId());

        QueryWrapper<VipCardCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vip_id", baseMemberVip.getId());
        List<VipCardCoupon> pageList = vipCardCouponService.list(queryWrapper);
        map.put("couponList", pageList);

//        //股东下发表 下发数据累加1
//        if (baseMemberVip.getType().equals("2")) {
//            QueryWrapper<ShareholderVipCard> query = new QueryWrapper<>();
//            query.eq("vip_id", baseMemberVip.getId());
//            ShareholderVipCard shareholderVipCard = shareholderVipCardService.getOne(query);
//            int hasBeenIssued = ToolsUtils.getNumeric(shareholderVipCard.getHasBeenIssued());
//            shareholderVipCard.setHasBeenIssued(String.valueOf(hasBeenIssued + 1));
//            shareholderVipCardService.updateById(shareholderVipCard);
//        }
        return Result.OK(map);
    }

    /**
     * 会员领取分享的优惠劵
     *
     * @param receiveId 收卡人ID
     * @param vipId     贵宾卡ID
     */
    @AutoLog(value = "全部贵宾卡-会员领取分享的优惠劵")
    @ApiOperation(value = "全部贵宾卡-会员领取分享的优惠劵", notes = "全部贵宾卡-会员领取分享的优惠劵")
    @GetMapping(value = "/receiveCoupon")
    @Transactional(rollbackFor = JeecgBootException.class)//事物
    public Result<?> receiveCoupon(String receiveId, String vipId) {

        BaseMemberVip baseMemberVip = baseMemberVipService.getById(vipId);

        baseMemberVipService.updateById(baseMemberVip);

        QueryWrapper<BaseMemberVip> queryVip = new QueryWrapper<>();
        queryVip.eq("send_vip_id", baseMemberVip.getId());
        queryVip.eq("member_id", receiveId);
        BaseMemberVip receiveMemberVip = baseMemberVipService.getOne(queryVip);
        if (receiveMemberVip != null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("您已经领取了贵宾卡，不能重复领取！");
        }

        receiveMemberVip = new BaseMemberVip();
        BeanUtils.copyProperties(baseMemberVip, receiveMemberVip);
        receiveMemberVip.setMemberId(receiveId);


        receiveMemberVip.setId(null);
        baseMemberVipService.save(receiveMemberVip);
        VipcardDrawRecord vipcardDrawRecord = new VipcardDrawRecord();
        vipcardDrawRecord.setCreateBy("");
        vipcardDrawRecord.setCreateTime(new Date());
        vipcardDrawRecord.setMemberId(receiveId);
        vipcardDrawRecord.setStoreId(baseMemberVip.getStoreId());
        vipcardDrawRecord.setVipId(getVipId(baseMemberVip.getStoreId(), receiveMemberVip.getCardId()));
        vipcardDrawRecord.setDrawDate(new Date());
        vipcardDrawRecord.setRemark("AllVipcardController receiveCoupon");
        vipcardDrawRecord.setId(receiveMemberVip.getIssuingRecordsId());

        vipcardDrawRecordService.save(vipcardDrawRecord);
        System.out.println(DebugUtils.showNullFiled(vipcardDrawRecord) + "is null");

        QueryWrapper<VipCardCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vip_id", baseMemberVip.getId());
        List<VipCardCoupon> pageList = vipCardCouponService.list(queryWrapper);
        for (VipCardCoupon bean : pageList) {
            VipCardCoupon vipCardCoupon = new VipCardCoupon();
            BeanUtils.copyProperties(bean, vipCardCoupon);
            vipCardCoupon.setVipId(receiveMemberVip.getId());
            vipCardCouponService.save(vipCardCoupon);
        }

//        //分享的卡 不更新发卡记录表 如果是股东拓客卡 要更新股东发卡记录
//        if (type.equals("2")) {
//            QueryWrapper<ShareholderVipCard> query = new QueryWrapper<>();
//            query.eq("vip_id", baseMemberVip.getId());
//            ShareholderVipCard shareholderVipCard = shareholderVipCardService.getOne(query);
//            int alreadyGet = ToolsUtils.getNumeric(shareholderVipCard.getAlreadyGet());
//            shareholderVipCard.setAlreadyGet(String.valueOf(alreadyGet + 1));
//            shareholderVipCardService.updateById(shareholderVipCard);
//        }

        return Result.OK("领取成功！");
    }

    /**
     * 会员模块领取下发的卡  只能分享的卡不能领取
     *
     * @param vipId 贵宾卡ID
     */
    @AutoLog(value = "全部贵宾卡-领取模块下发贵宾卡")
    @ApiOperation(value = "全部贵宾卡-领取模块下发贵宾卡", notes = "全部贵宾卡-领取模块下发贵宾卡")
    @GetMapping(value = "/memberReceiveCoupon")
    @Transactional(rollbackFor = JeecgBootException.class)//事物
    public Result<?> memberReceiveCoupon(String vipId) {
        BaseMemberVip baseMemberVip = baseMemberVipService.getById(vipId);
//        if (baseMemberVip.getType().equals("1")) {
//            baseMemberVip.setType("2");
//            baseMemberVipService.updateById(baseMemberVip);
//            //
//            QueryWrapper<IssuingRecords> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("vip_id", vipId);
//            IssuingRecords issuing = issuingRecordsService.getOne(queryWrapper);
//            issuing.setQuantityReceived(issuing.getCirculation());
//            issuingRecordsService.updateById(issuing);
        return Result.OK("领取成功");
//        } else {
//            return Result.error("无法领取！");
//        }
    }

    /**
     * 会员扫码领取优惠劵
     * 系统要生成一个二维码 里面有 time(yyyy-MM-dd HH:mm:ss) 和 vipId 两个属性参数  获取后调用此接口  time为当前时间 超过当前时间10分钟后失效
     *
     * @param staffId 会员ID
     * @param vipId   贵宾卡ID
     * @param time    二维码时间
     */
    @AutoLog(value = "全部贵宾卡-会员扫码领取优惠劵")
    @ApiOperation(value = "全部贵宾卡-会员扫码领取优惠劵", notes = "全部贵宾卡-会员扫码领取优惠劵")
    @GetMapping(value = "/memberScanCode")
    @Transactional(rollbackFor = JeecgBootException.class)//事物
    public Result<?> memberScanCode(String staffId, String vipId, String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nowDate = simpleDateFormat.parse(time);
        long nd = 1000 * 24 * 60 * 60;//每天毫秒数
        long nh = 1000 * 60 * 60;//每小时毫秒数
        long nm = 1000 * 60;//每分钟毫秒数
        Date endDate = new Date();
        long diff = endDate.getTime() - nowDate.getTime(); //获得两个时间的毫秒时间差异
        long min = diff % nd % nh / nm;  // 计算差多少分钟
        if (min > 10) {
            return Result.error("二维码超过了10分钟 已失效");
        }

        AllVipcard allVipcard = allVipcardService.getById(vipId);
        //把当前贵宾卡和会员卡状态 赋值到新的表
        BaseMemberVip baseMemberVip = new BaseMemberVip();
        BeanUtils.copyProperties(allVipcard, baseMemberVip);
        baseMemberVip.setId(null);
//        baseMemberVip.setStatus("1");
//        baseMemberVip.setType("2");
        baseMemberVip.setMemberId(staffId);
//        baseMemberVip.setNum(1);
        baseMemberVipService.save(baseMemberVip);
        VipcardDrawRecord vipcardDrawRecord = new VipcardDrawRecord();
        vipcardDrawRecord.setCreateBy("xcx");
        vipcardDrawRecord.setCreateTime(new Date());
        vipcardDrawRecord.setMemberId(staffId);
        vipcardDrawRecord.setStoreId(storeId);
        vipcardDrawRecord.setVipId(allVipcard.getId());
        vipcardDrawRecord.setDrawDate(new Date());
        vipcardDrawRecord.setIssuingRecordsId(baseMemberVip.getIssuingRecordsId());
        vipcardDrawRecord.setRemark("AllVipcardController receiveCoupon");
        vipcardDrawRecordService.save(vipcardDrawRecord);

        QueryWrapper<VipCardCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vip_id", vipId);
        List<VipCardCoupon> pageList = vipCardCouponService.list(queryWrapper);
        for (VipCardCoupon bean : pageList) {
            BaseMemberVipCoupon baseMemberVipCoupon = new BaseMemberVipCoupon();
            BeanUtils.copyProperties(bean, baseMemberVipCoupon);
            baseMemberVipCoupon.setId(null);
//            baseMemberVipCoupon.setVipId(baseMemberVip.getId());
            baseMemberVipCouponService.save(baseMemberVipCoupon);
        }

        //会员扫码 暂不生成下发记录
        return Result.OK("领取成功");
    }

    /**
     * 会员领取新人卡
     * coupleCoupon
     * 会员领取新人卡
     *
     * @param staffId 会员ID
     */
    @AutoLog(value = "全部贵宾卡-会员领取新人卡")
    @ApiOperation(value = "全部贵宾卡-会员领取新人卡", notes = "全部贵宾卡-会员领取新人卡")
    @GetMapping(value = "/coupleCoupon")
    @Transactional(rollbackFor = JeecgBootException.class)//事物
    public Result<?> coupleCoupon(String staffId) {
        QueryWrapper<AllVipcard> query = new QueryWrapper<>();
        query.eq("card_type", "新人卡");
        AllVipcard allVipcard = allVipcardService.getOne(query);

        if (allVipcard == null) {
            return Result.error("没有新人卡");
        }
        //把当前贵宾卡和会员卡状态 赋值到新的表
        BaseMemberVip baseMemberVip = new BaseMemberVip();
        BeanUtils.copyProperties(allVipcard, baseMemberVip);
        baseMemberVip.setId(null);
//        baseMemberVip.setStatus("1");
//        baseMemberVip.setType("2");
        baseMemberVip.setMemberId(staffId);
//        baseMemberVip.setNum(1);
        baseMemberVipService.save(baseMemberVip);
        VipcardDrawRecord vipcardDrawRecord = new VipcardDrawRecord();
        vipcardDrawRecord.setCreateBy("xcx");
        vipcardDrawRecord.setCreateTime(new Date());
        vipcardDrawRecord.setIssuingRecordsId(baseMemberVip.getIssuingRecordsId());
        vipcardDrawRecord.setMemberId(staffId);
        vipcardDrawRecord.setStoreId(baseMemberVip.getStoreId());
        vipcardDrawRecord.setVipId(allVipcard.getId());
        vipcardDrawRecord.setDrawDate(new Date());
        vipcardDrawRecord.setRemark("AllVipcardController coupleCoupon");
        vipcardDrawRecordService.save(vipcardDrawRecord);

        QueryWrapper<VipCardCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vip_id", allVipcard.getId());
        List<VipCardCoupon> pageList = vipCardCouponService.list(queryWrapper);
        for (VipCardCoupon bean : pageList) {
            BaseMemberVipCoupon baseMemberVipCoupon = new BaseMemberVipCoupon();
            BeanUtils.copyProperties(bean, baseMemberVipCoupon);
            baseMemberVipCoupon.setId(null);
//            baseMemberVipCoupon.setVipId(baseMemberVip.getId());
            baseMemberVipCouponService.save(baseMemberVipCoupon);
        }
        return Result.OK("领取成功");
    }

    /**
     * 会员查看可领取的贵宾卡
     * getStaffSendVip
     *
     * @param memberId 会员ID
     */
    @AutoLog(value = "全部贵宾卡-会员查看可领取的贵宾卡")
    @ApiOperation(value = "全部贵宾卡-会员查看可领取的贵宾卡", notes = "全部贵宾卡-会员查看可领取的贵宾卡")
    @GetMapping(value = "/getMemberSendVip")
    public Result<?> getMemberSendVip(String memberId,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                      HttpServletRequest req) {
        //HttpServletRequest req
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<BaseMemberVip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("status", "1");
        queryWrapper.eq("type", "1");
        Page<BaseMemberVip> page = new Page<>(pageNo, pageSize);
        IPage<BaseMemberVip> pageList = baseMemberVipService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查看会员已领取的贵宾卡
     * getMemberVip
     *
     * @param memberId 会员ID
     */
    @AutoLog(value = "全部贵宾卡-查看会员已领取的贵宾卡")
    @ApiOperation(value = "全部贵宾卡-查看会员已领取的贵宾卡", notes = "全部贵宾卡-查看会员已领取的贵宾卡")
    @GetMapping(value = "/getMemberVip")
    public Result<?> getMemberVip(String memberId,
                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                  HttpServletRequest req) {
        //HttpServletRequest req
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        QueryWrapper<BaseMemberVip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("status", "1");
        queryWrapper.eq("type", "2");
        //QueryGenerator.initQueryWrapper(queryWrapper,baseMemberVip, req.getParameterMap());
        Page<BaseMemberVip> page = new Page<>(pageNo, pageSize);
        IPage<BaseMemberVip> pageList = baseMemberVipService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查看会员可以分享的贵宾卡
     *
     * @param memberId 会员ID
     */
    @AutoLog(value = "全部贵宾卡-查看会员可以分享的贵宾卡")
    @ApiOperation(value = "全部贵宾卡-查看会员可以分享的贵宾卡", notes = "全部贵宾卡-查看会员可以分享的贵宾卡")
    @GetMapping(value = "/getMemberShareVip")
    public Result<?> getMemberShareVip(String memberId, BaseMemberVip baseMemberVip,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        //HttpServletRequest req
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        QueryWrapper<BaseMemberVip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("status", "1");
        queryWrapper.eq("type", "3");
        QueryGenerator.initQueryWrapper(queryWrapper, baseMemberVip, req.getParameterMap());
        Page<BaseMemberVip> page = new Page<>(pageNo, pageSize);
        IPage<BaseMemberVip> pageList = baseMemberVipService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查看可以分享的股东拓客卡
     * getStockVip
     *
     * @param stockId 股东ID
     */
    @AutoLog(value = "全部贵宾卡-查看可以分享的股东拓客卡")
    @ApiOperation(value = "全部贵宾卡-查看可以分享的股东拓客卡", notes = "全部贵宾卡-查看可以分享的股东拓客卡")
    @GetMapping(value = "/getStockVip")
    public Result<?> getStockVip(String stockId, BaseMemberVip baseMemberVip,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        QueryWrapper<BaseMemberVip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("member_id", stockId);
        queryWrapper.eq("status", "2");
        queryWrapper.eq("type", "3");
        QueryGenerator.initQueryWrapper(queryWrapper, baseMemberVip, req.getParameterMap());
        Page<BaseMemberVip> page = new Page<>(pageNo, pageSize);
        IPage<BaseMemberVip> pageList = baseMemberVipService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 根据贵宾卡ID获取优惠劵
     *
     * @param vipId 贵宾卡ID
     */
    @AutoLog(value = "全部贵宾卡-查看已经领取的优惠劵")
    @ApiOperation(value = "全部贵宾卡-查看已经领取的优惠劵", notes = "全部贵宾卡-查看已经领取的优惠劵")
    @GetMapping(value = "/getReceiveCoupon")
    public Result<?> getReceiveCoupon(String vipId,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<BaseMemberVipCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vip_id", vipId);
        Page<BaseMemberVipCoupon> page = new Page<>(pageNo, pageSize);
        IPage<BaseMemberVipCoupon> pageList = baseMemberVipCouponService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 股东贵宾卡下发记录
     * stockShareVip
     */
    @AutoLog(value = "全部贵宾卡-股东贵宾卡下发记录")
    @ApiOperation(value = "全部贵宾卡-股东贵宾卡下发记录", notes = "全部贵宾卡-股东贵宾卡下发记录")
    @GetMapping(value = "/stockShareVip")
    public Result<?> queryPageList(ShareholderVipCard shareholderVipCard,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        QueryWrapper<ShareholderVipCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, shareholderVipCard, req.getParameterMap());
        Page<ShareholderVipCard> page = new Page<ShareholderVipCard>(pageNo, pageSize);
        IPage<ShareholderVipCard> pageList = shareholderVipCardService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 删除会员卡片
     */
    @AutoLog(value = "全部贵宾卡-删除会员卡片")
    @ApiOperation(value = "全部贵宾卡-删除会员卡片", notes = "全部贵宾卡-删除会员卡片")
    @GetMapping(value = "/deleteCard")
    public Result<?> deleteCard(@RequestParam(name = "cardid", defaultValue = "") String cardId,
                                @RequestParam(name = "memberId", defaultValue = "1") String memberId,
                                HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
//        AllVipcard card =
        IssuingRecords record = issuingRecordsService.getById(cardId);
        String vipId = record.getVipId();
        AllVipcard card = allVipcardService.getById(vipId);

        if (card == null) {
            return Result.error("没有找到卡");
        }
        Integer vcardId = card.getCardId();
        List<BaseMemberVip> list = baseMemberVipService.list(new QueryWrapper<BaseMemberVip>().eq("card_id", vcardId).eq("store_id", storeId).eq("member_id", memberId));
        List<String> idList = new ArrayList<>();
        for (BaseMemberVip ele : list) {
            idList.add(ele.getId());
        }
        issuingRecordsService.removeById(record.getId());
        baseMemberVipService.removeByIds(idList);
//        allVipcardService.removeById(card.getId());
        return Result.OK();
    }

    /**
     * 投放通用卡给会员
     */
    @AutoLog(value = "全部贵宾卡-投放通用卡给会员")
    @ApiOperation(value = "全部贵宾卡-投放通用卡给会员", notes = "全部贵宾卡-投放通用卡给会员")
    @GetMapping(value = "/castGeneral")
    public Result<?> castGeneral4Member(@RequestParam(name = "vipId", defaultValue = "1") String vipId,
                                        @RequestParam(name = "memberId", defaultValue = "1") String memberId,
                                        HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        AllVipcard card = allVipcardService.getById(vipId);
        if (card == null) {
            return Result.error("没有找到卡");
        } else {
            if (!"通用卡".equals(card.getCardType())) {
                return Result.error("只有通用卡才能投放");
            }
        }
        String[] ids = memberId.split(",");

        if (ids.length > 1) {

        }

        QueryWrapper<VipCardCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vip_id", vipId);
        List<VipCardCoupon> pageList = vipCardCouponService.list(queryWrapper);
        if (pageList.size() == 0) {
            return Result.error("该贵宾卡缺少优惠券，请设置！");
        }

        card.setCreditNumber(card.getCreditNumber() + ids.length);
        allVipcardService.updateById(card);
        List<BaseMemberVipCoupon> bmvList = new ArrayList<>();
        List<CastCardRecord> recordList = new ArrayList<>();
        for (String vId : ids) {
            BaseMemberVip baseMemberVip = new BaseMemberVip();
            BeanUtils.copyProperties(card, baseMemberVip);
            baseMemberVip.setId(null);
            baseMemberVip.setCreateBy(null);
            baseMemberVip.setCreateTime(null);
            baseMemberVip.setUpdateBy(null);
            baseMemberVip.setUpdateTime(null);
            baseMemberVip.setMemberId(vId);
            baseMemberVip.setCardId(card.getCardId());

            baseMemberVipService.save(baseMemberVip);
//            VipcardDrawRecord vipcardDrawRecord = new VipcardDrawRecord();
//            vipcardDrawRecord.setCreateBy("xcx");
//            vipcardDrawRecord.setCreateTime(new Date());
//            vipcardDrawRecord.setMemberId(vId);
//            vipcardDrawRecord.setStoreId(storeId);
//            vipcardDrawRecord.setVipId(card.getId());
//            vipcardDrawRecordService.save(vipcardDrawRecord);

            for (VipCardCoupon bean : pageList) {
                BaseMemberVipCoupon baseMemberVipCoupon = new BaseMemberVipCoupon();
                BeanUtils.copyProperties(bean, baseMemberVipCoupon);
                baseMemberVipCoupon.setId(null);
//            baseMemberVipCoupon.setSysOrgCode(bean.getSysOrgCode());

                String couponId = bean.getCouponId();
                CouponManagement coupon = couponManagementService.getById(couponId);
                BeanUtils.copyProperties(coupon, baseMemberVipCoupon);
                baseMemberVipCoupon.setMemberVipId(baseMemberVip.getId());
                baseMemberVipCoupon.setMemberId(vId);
                baseMemberVipCoupon.setId(null);
                baseMemberVipCoupon.setCreateBy(null);
                baseMemberVipCoupon.setCreateTime(null);
                baseMemberVipCoupon.setUpdateBy(null);
                baseMemberVipCoupon.setUpdateTime(null);
                bmvList.add(baseMemberVipCoupon);

            }


            CastCardRecord record = new CastCardRecord();
            MemberManagement member = memberManagementService.getById(vId);
            BeanUtils.copyProperties(card, record);
//        BeanUtils.copyProperties(member,record);

            record.setId(null);
            record.setCreateBy(null);
            record.setCreateTime(null);
            record.setUpdateBy(null);
            record.setUpdateTime(null);
            record.setDrawTime(Date.from(Instant.now()));
            record.setMemberId(vId);
            record.setMemberName(member.getName());
            record.setMemberPhone(member.getPhone());
            record.setVipId(card.getId());
            record.setOperator(ToolsUtils.getUerName());
//        AllVipcard card = allVipcardService.getById(vipId);
//
            //核销时更新进店时间？
            record.setVipId(vipId);
            record.setVipName(card.getCardName());
            record.setCardId(String.valueOf(card.getCardId()));
            recordList.add(record);

        }
        baseMemberVipCouponService.saveBatch(bmvList);
        castCardRecordService.saveBatch(recordList);


        return Result.OK();
    }

    /**
     * 删除发送的通用卡会员卡片
     */
    @AutoLog(value = "全部贵宾卡-删除发送的通用卡会员卡片")
    @ApiOperation(value = "全部贵宾卡-删除发送的通用卡会员卡片", notes = "删除发送的通用卡会员卡片")
    @GetMapping(value = "/deleteGeneralCard")
    public Result<?> deleteGeneralCard(@RequestParam(name = "vipId", defaultValue = "1") String vipId,
                                       @RequestParam(name = "memberId", defaultValue = "1") String memberId,
                                       HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
//        AllVipcard card =
        List<AllVipcard> list1 = allVipcardService.list(new QueryWrapper<AllVipcard>().eq("id", vipId).eq("store_id", storeId));
        if (list1.size() == 0) {
            return Result.error("没有找到卡");
        } else if (list1.size() > 1) {
            return Result.error("找到多张卡");
        }
        AllVipcard card = list1.get(0);

        List<CastCardRecord> cards = castCardRecordService.list(new QueryWrapper<CastCardRecord>().eq("store_id", storeId).eq("member_id", memberId).eq("vip_id", vipId));
        List<String> cIdList = new ArrayList<>();
        for (CastCardRecord ele : cards) {
            cIdList.add(ele.getId());
        }

        List<BaseMemberVip> vips = baseMemberVipService.list(new QueryWrapper<BaseMemberVip>().eq("store_id", storeId).eq("member_id", memberId).eq("card_id", card.getCardId()));
        List<Integer> vIdList = new ArrayList<>();
        for (BaseMemberVip ele : vips) {
            vIdList.add(ele.getCardId());
        }
        baseMemberVipService.removeByIds(vIdList);
        castCardRecordService.removeByIds(cIdList);
//        allVipcardService.removeById(vipId);


        return Result.OK();
    }


    /**
     * 发卡详情
     */
    @AutoLog(value = "全部贵宾卡-发卡详情")
    @ApiOperation(value = "全部贵宾卡-发卡详情", notes = "全部贵宾卡-发卡详情")
    @GetMapping(value = "/castCardDetail")
    public Result<?> castCardDetail(CastCardRecord castCardRecord,
                                    @RequestParam(name = "vipid", defaultValue = "1") String vipId,
                                    @RequestParam(name = "memberId", defaultValue = "1") String memberId,
                                    @RequestParam(name = "keyword", defaultValue = "") String cardName,
                                    @RequestParam(name = "memberName", defaultValue = "") String memberName,
                                    @RequestParam(name = "memberPhone", defaultValue = "") String memberPhone,
                                    @RequestParam(name = "startDate", required = false, defaultValue = "") String startDate,
                                    @RequestParam(name = "endDate", required = false, defaultValue = "") String endDate,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {

        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
//        AllVipcard card =
//        List<AllVipcard> list1 = allVipcardService.list(new QueryWrapper<AllVipcard>().eq("card_id", cardId).eq("store_id", storeId));
//        if (list1.size() == 0) {
//            return Result.error("没有找到卡");
//        } else if (list1.size() > 1) {
//            return Result.error("找到多张卡");
//        }
        //AllVipcard card = list1.get(0);
        if (!StringUtils.isBlank(cardName) || !StringUtils.isBlank(memberPhone) || !StringUtils.isBlank(memberName) || !StringUtils.isBlank(startDate) || !StringUtils.isBlank(endDate)) {

            if (!StringUtils.isBlank(memberName)) {
                memberName = memberName.replaceAll("\\*", "");
            }
            if (!StringUtils.isBlank(memberPhone)) {
                memberPhone = memberPhone.replaceAll("\\*", "");
            }

            List<CastCardRecord> castCardRecords = castCardRecordService.listEx(storeId, cardName, memberName, memberPhone, startDate, endDate, pageNo, pageSize);
            int total = castCardRecordService.countEx(storeId, cardName, memberName, memberPhone, startDate, endDate);
            Map<String, Object> result = new HashMap<>();
            result.put("current", 1);
            result.put("total", total);
            List<Map<String, Object>> list = new ArrayList<>();

            for (CastCardRecord record : castCardRecords) {
                String vipId1 = record.getVipId();
                AllVipcard vipcard = allVipcardService.getById(vipId1);
                Map<String, Object> map1 = org.jeecg.modules.util.BeanUtils.bean2Map(record);
                if (vipcard != null) {
                    map1.put("cardId", vipcard.getCardId());
                    map1.put("cardName", vipcard.getCardName());
                    map1.put("isFree", vipcard.getIsFree());
                    map1.put("ticketNum", vipcard.getTicketNum());
                    map1.put("cardPrice", vipcard.getSellingPrice());
                }
                list.add(map1);
            }

            result.put("records", list);
            return Result.OK(result);
        } else {
            QueryWrapper<CastCardRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("store_id", storeId);
            QueryGenerator.initQueryWrapper(queryWrapper, castCardRecord, req.getParameterMap());
            Map<String, String[]> map = req.getParameterMap();
            Page<CastCardRecord> page = new Page<>(pageNo, pageSize);
            IPage<CastCardRecord> pageList = castCardRecordService.page(page, queryWrapper);

            List<Map<String, Object>> list = new ArrayList<>();

            for (CastCardRecord record : pageList.getRecords()) {
                String vipId1 = record.getVipId();
                AllVipcard vipcard = allVipcardService.getById(vipId1);
                Map<String, Object> map1 = org.jeecg.modules.util.BeanUtils.bean2Map(record);
                if (vipcard != null) {
                    map1.put("cardId", vipcard.getCardId());
                    map1.put("cardName", vipcard.getCardName());
                    map1.put("isFree", vipcard.getIsFree());
                    map1.put("ticketNum", vipcard.getTicketNum());
                    map1.put("cardPrice", vipcard.getSellingPrice());
                }
                list.add(map1);
            }
            Map<String, Object> result = org.jeecg.modules.util.BeanUtils.bean2Map(pageList);
            result.put("records", list);
            return Result.OK(result);
        }
    }

    /**
     * 通过id查询发卡记录
     */
    @AutoLog(value = "全部贵宾卡-领取记录")
    @ApiOperation(value = "全部贵宾卡-领取记录", notes = "全部贵宾卡-领取记录")
    @GetMapping(value = "/queryDetail")
    public Result<?> queryDetail(@RequestParam(name = "cardId", defaultValue = "") String cardId,
                                 // @RequestParam(name = "memberId", defaultValue = "1") String memberId,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<BaseMemberVip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId).eq("card_id", cardId);
        QueryGenerator.initQueryWrapper(queryWrapper, new BaseMemberVip(), req.getParameterMap());

        Page<BaseMemberVip> page = new Page<>(pageNo, pageSize);
        IPage<BaseMemberVip> pageList = baseMemberVipService.page(page, queryWrapper);

        return Result.OK(pageList);
    }

    private String getVipId(String storeId, Integer cardId) {
        List<AllVipcard> list = allVipcardService.list(new QueryWrapper<AllVipcard>().eq("store_id", storeId).eq("card_id", cardId));
        if (list.size() == 1) {
            return list.get(0).getId();
        }
        return "";
    }
}
